/**
 * 融云通讯接口
 *
 */
"use struct";
var RongCloudWebkit = function() {};

/**
 * 融云通讯接口实现
 * @type {[type]}
 */
var rcWebToolket = (function($, $rc) {
  $rc.fn = $.extend({}, RongCloudWebkit.prototype);

  $rc.setting = {
    __DEV__: false,
    host: "https://interface.ultimavip.cn/",
    // appKey: 'tdrvipksr0zm5',
    appKey: "k51hidwqke0sb",
    actions: {
      getToken: "/website/getRongToken"
    }
  };

	if (location.host.indexOf('ultimavip.cn') >= 0) {
		$rc.setting.host = 'https://interface.ultimavip.cn/';
		$rc.setting.appKey = 'tdrvipksr0zm5';
	} else {
		$rc.setting.host = 'http://testabc.ultimablack.cn/';
		$rc.setting.appKey = 'k51hidwqke0sb';
	}

  //绑定属性
  (function() {
    var target = null;
    var userId = null;
    Object.defineProperty($rc.setting, "target", {
      get: function() {
        target = sessionStorage.getItem(
          $rc.setting.appKey
            .split("")
            .reverse()
            .join("")
        );
        return target || "W001";
      },
      set: function(value) {
        target = value;
      }
    });
    Object.defineProperty($rc.setting, "userId", {
      get: function() {
        var userId = localStorage.getItem($rc.setting.appKey + "userId");
        return userId;
      },
      set: function(value) {
        userId = value;
      }
    });
  })();

  /**
   * 请求代码封装
   * @param  {[type]} url    [description]
   * @param  {[type]} type   [description]
   * @param  {[type]} data   [description]
   * @param  {[type]} config [description]
   * @return {[type]}        [description]
   */
  $rc.request = function(url, type, data, config) {
    var params = {
      crossDomain: true,
      type: type,
      url: url,
      data: data,
      fail: function(error) {
        console.log(error);
      }
    };
    if (config) {
      params = Object.assign({}, params, config);
    }
    return $.ajax(params);
  };

  //绑定方法
  var method = ["get", "post", "put", "delete"];
  $.each(method, function(i, v) {
    $rc.request[v] = function(url, data, config) {
      return $rc.request(url, v, data, config);
    };
  });

  /**
   * 初始化
   * @return {[type]} [description]
   */

  $rc.fn.init = function() {
    //鑾峰彇uuid and  token

    this.watches = [];
  };

  /**
   * 连接到server
   *
   * @param  {[type]} argument [description]
   * @return {[type]}          [description]
   */
  $rc.fn.conn2Server = function(argument) {
    var self = this;
    this.getToken().then(
      function(res) {
        if (!res) {
          return alert(res.msg || "获取token服务器异常");
        }

        //连接
        self.connect({})()(res.token, {});
      },
      function(error) {
        console.log(error);
      }
    );
  };

  /**
   * 发起连接
   * @param  {[type]} hanlder [description]
   * @return {[type]}         [description]
   */
  $rc.fn.connect = function(hanlder) {
    RongIMClient.init($rc.setting.appKey);
    var self = this;

    var defaults = {};
    defaults[RongIMLib.ConnectionStatus.CONNECTED] = function() {
      console.log("连接成功");
    };

    defaults[RongIMLib.ConnectionStatus.CONNECTING] = function() {
      console.log("连接中...");
    };
    defaults[RongIMLib.ConnectionStatus.DISCONNECTED] = function() {
      console.log("断开连接...");
    };
    defaults[
      RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT
    ] = function() {
      console.log("其他设备登录...");
    };
    defaults[RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE] = function() {
      console.log("网路不可用...");
    };

    var handlers = $.extend({}, defaults, hanlder);
    //状态监测
    RongIMClient.setConnectionStatusListener({
      onChanged: function(status) {
        handlers[status] && handlers[status]();
      }
    });

    return function(callback) {
      var defaults = {};
      defaults[RongIMClient.MessageType.TextMessage] = function() {
        // console.log("TextMessage", this);
      };
      defaults[RongIMClient.MessageType.ImageMessage] = function() {
        // console.log("ImageMessage", this);
      };
      defaults[RongIMClient.MessageType.UnknownMessage] = function() {
        // console.log(this)
      };
      var callbacks = $.extend({}, defaults, callback);

      RongIMClient.setOnReceiveMessageListener({
        // 接收到的消息
        onReceived: function(message) {
          // 判断消息类型
          // jj
          var extra =
            message.content.extra && JSON.parse(message.content.extra);
          $rc.setting.target = message.senderUserId;
          $rc.setting.userId = extra.userId;
          sessionStorage.setItem(
            $rc.setting.appKey
              .split("")
              .reverse()
              .join(""),
            message.senderUserId
          );
          localStorage.setItem($rc.setting.appKey + "userId", extra.userId);

          self.watches.length > 0 &&
            $.each(self.watches, function() {
              this.call(message, message.messageType, message);
            });
          callbacks[message.messageType] &&
            callbacks[message.messageType].call(message);
        }
      });

      return function(token, connErrorHandler) {
        //RongIMClient.init($rc.setting.appKey);

        //连接融云
        RongIMClient.connect(
          token,
          {
            onSuccess: function(userId) {
              console.log("Login successfully." + userId);
            },
            onTokenIncorrect: function() {
              console.log("token鏃犳晥");
            },
            onError: function(errorCode) {
              var defaults = {};
              defaults[RongIMLib.ErrorCode.TIMEOUT] = function() {
                console.log("超时");
              };
              defaults[RongIMLib.ErrorCode.UNKNOWN_ERROR] = function() {
                console.log("未知错误");
              };
              defaults[
                RongIMLib.ErrorCode.UNACCEPTABLE_PaROTOCOL_VERSION
              ] = function() {
                console.log("涓嶅彲鎺ュ彈鐨勫崗璁増鏈�");
              };
              defaults[RongIMLib.ErrorCode.IDENTIFIER_REJECTED] = function() {
                console.log("appkey涓嶆纭�");
              };
              defaults[RongIMLib.ErrorCode.SERVER_UNAVAILABLE] = function() {
                console.log("鏈嶅姟鍣ㄤ笉鍙敤");
              };

              var hanldersError = $.extend({}, defaults, connErrorHandler);
              hanldersError(errorCode);
            }
          }
        );
      };
    };
  };

  /**
   * 获取token
   * @return {[type]} [description]
   */
  $rc.fn.getToken = function() {
    if ($rc.setting.__DEV__) {
      var defer = $.Deferred();
      setTimeout(function() {
        defer.resolve({
          success: true,
          data:
            "yo5CvV9yoePgY1WB61tl0pB4nogYFOsaBKMJ2gEOGTzQC0Hdvj1rv1LVtVi8EXg317s/yoH3bdTJLWv9SHgDfNHD/SAhK2hH"
        });
      }, 2000);
      return defer.promise();
    }
    var defer = $.Deferred();
    setTimeout(function() {
      var data = localStorage.getItem($rc.setting.appKey);
      if (data) {
        return defer.resolve(JSON.parse(data));
      }

      $rc.request
        .get($rc.setting.host + $rc.setting.actions.getToken)
        .then(function(res) {
          localStorage.setItem($rc.setting.appKey, res.data.token);
          defer.resolve(res && res.success && JSON.parse(res.data.token));
        });
    }, 5);

    return defer.promise();
  };

  /**
   * 发送消息
   * @param  {[type]} type    [description]
   * @param  {[type]} message [description]
   * @return {[type]}         [description]
   */
  $rc.fn.send = function(type, message) {
    var defer = $.Deferred();
    var user = JSON.parse(localStorage.getItem($rc.setting.appKey));
    //与管家私聊  咨询不应该是 多人瞎比比
    var extra = JSON.stringify({
      userId: $rc.setting.userId,
      openId: user.userId,
      source: 3
    });

    var msss = {
      content: message,
      extra: extra
    };
    if (type == 3) {
      // msss.content = message.content;
      msss.imageUri = message.imageUri;
    }
    var msg = $rc.getMessage(type, msss);
    RongIMClient.getInstance().sendMessage(
      RongIMLib.ConversationType.PRIVATE,
      $rc.setting.target,
      msg,
      {
        onSuccess: function(msg) {
          console.log("send success", msg);
          defer.resolve(arguments);
        },
        onError: function(error) {
          console.log("send error", error);
          $rc.sendErrorHandler(error);
          defer.reject(error);
        }
      }
    );
    return defer.promise();
  };

  $rc.sendErrorHandler = function(error) {
    var handers = {};
    handers[RongIMLib.ErrorCode.TIMEOUT] = "超时";
    handers[RongIMLib.ErrorCode.UNKNOWN_ERROR] = "未知错误";
    handers[RongIMLib.ErrorCode.REJECTED_BY_BLACKLIST] =
      "在黑名单中，无法向对方发送消息";
    handers[RongIMLib.ErrorCode.NOT_IN_DISCUSSION] = "不在讨论组中";
    handers[RongIMLib.ErrorCode.NOT_IN_GROUP] = "不在群组中";
    handers[RongIMLib.ErrorCode.NOT_IN_CHATROOM] = "不在聊天室中";
    handers[error]
      ? alert(handers[error])
      : alert("消息发送失败，请联系技术人员");
  };
  /**
   * 获取消息
   * @param  {[type]} type [description]
   * @return {[type]}      [description]
   */
  $rc.getMessage = function(type, obj) {
    var messageType = {
      1: RongIMLib.TextMessage,
      3: RongIMLib.ImageMessage
    };
    return new messageType[type](obj);
  };
  /**
   * 发送文本消息
   * @return {[type]} [description]
   */
  $rc.fn.sendText = function(text) {
    return this.send(1, text);
  };

  /**
   * 发送图片消息
   * @param  {[type]} image [description]
   * @return {[type]}       [description]
   */
  $rc.fn.sendImage = function(image) {
    return this.send(3, image);
  };

  /**
   * 返回历史消息
   * @return {[type]} [description]
   */
  $rc.fn.getMessageList = function() {
    return this.menssagesList;
  };

  /**
   * 增加监控程序
   * @param {Function} fn [description]
   */
  $rc.fn.setWatch = function(fn) {
    this.watches.push(fn || $.noop);
  };

  /**
   * 暴露对象
   * @return {[type]} [description]
   */
  var init = function() {
    if (!(this instanceof init)) {
      return new init();
    }
  };
  $.extend(init.prototype, $rc.fn);
  $.extend(init, $rc);
  return init;
})(jQuery, new RongCloudWebkit());
